"""
环信操作代理
"""
import datetime
import json
from django.db import transaction

from .api import HxApi
from src.utils import record


class ImAgent:
    def __init__(self):
        self.im = HxApi()
        self.icgr = record.ChatgroupRecord()  # 群组
        self.imr = record.MessageRecord()  # 消息

    def create_course_task_chatGroup(self, **kwargs):
        """
        创建课程讨论组
        """
        groupname = kwargs.get("groupname")
        description = kwargs.get("description")
        owner = kwargs.get("owner")
        custom = kwargs.get("custom")
        # 创建讨论组
        chatgroup_info = {
            "groupname": groupname,
            "description": description,
            "owner": owner,
            "custom": custom
        }
        g_result = self.im.make_chatgroup(owner, **chatgroup_info)
        # 讨论组信息入库
        group_id = g_result.get("data").get("groupid")
        chatgroup_info = {
            "is_delete": 0,
            "disabled": 0,
            "group_id": group_id,
            "groupname": groupname
        }
        return self.icgr.create_record(**chatgroup_info)

    def join_chatGroup(self, **kwargs):
        """
        加入讨论组
        """
        username = kwargs.get("username")
        group_id = kwargs.get("group_id")
        return self.im.join_chatgroup(group_id=group_id,username=username)
